package com.lyj.job.handle;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyj.common.core.constants.CacheConstants;
import com.lyj.job.domain.exam.Exam;
import com.lyj.job.mapper.exam.ExamMapper;
import com.lyj.redis.service.RedisService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lyj.common.core.constants.Constants;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-09-08
 * Time: 11:24
 */
@Component
@Slf4j
public class ExamXxlJob {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {
        log.info("examListOrganizeHandler执行");
        //未完赛竞赛列表
        List<Exam> unFinishList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                        .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                                Exam::getEndTime)
                        .gt(Exam::getEndTime, LocalDateTime.now())
                        .eq(Exam::getStatus, Constants.TRUE)
                        .orderByDesc(Exam::getCreateTime));
        refreshCache(CacheConstants.EXAM_UNFINISHED_LIST, unFinishList);
        //历史竞赛列表
        List<Exam> historyExamList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                        Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(CacheConstants.EXAM_HISTORY_LIST, historyExamList);
    }
    public void refreshCache(String examListKey, List<Exam> examList) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap); //刷新详情缓存
        redisService.deleteObject(examListKey);
        redisService.rightPushAll(examListKey, examIdList); //刷新列表缓存
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

}
